<template>
  <div class="application-page" v-cloak>
    <div class="application-side">
      <span>申请入驻平台</span>
    </div>
    <div class="application-main">
      <div class="wrap">
        <div class="application-status" v-if="applicationState != 1 && pageState == 4">
          <el-row v-if="applicationState == 3">
            <span>暂未申请，马上</span>
            <el-button type="text" @click="goApplication()">申请</el-button>
          </el-row>
          <el-row v-if="applicationState == 4">
            <span>商户暂未分配产品,请联系平台管理员</span>
          </el-row>
          <div class="application-status-line" v-if="applicationState == 0 || applicationState == 2">
            <div style="height: 200px;">
              <el-steps direction="vertical" :active="2">
                <el-step title="提交申请" icon="el-icon-upload"></el-step>
                <el-step v-if="applicationState == 2" title="已驳回" icon="el-icon-warning"></el-step>
                <el-step v-else title="审核中" icon="el-icon-time"></el-step>
                <el-step title="通过" description icon="el-icon-circle-check"></el-step>
              </el-steps>
            </div>
            <div class="application-status-des">
              <div class="application-reject">
                <el-button type="primary" @click="look()">查看提交信息</el-button>
                <el-button type="primary" v-if="applicationState == 2" @click="dialogVisible = true">查看驳回原因</el-button>
                <el-button type="primary" v-if="applicationState == 2" @click="editForm()">修改提交资料</el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="application-form" v-if="pageState != 4">
          <el-form :label-position="labelPosition" :model="changeFormData" :rules="rules" :hide-required-asterisk = 'pageState != 0 && pageState!=2' ref="formData" label-width="150px" class="add-user-form" size="small">

            <el-form-item label="商户名称：" prop="name">
              <p v-if="pageState == 1">{{formData.name}}</p>
              <el-input v-else class="add-input" v-model="changeFormData.name" clearable
                        @keyup.native='replace(changeFormData.name,changeFormData,"name")' maxlength = '50'></el-input>
            </el-form-item>

            <el-form-item label="联系人姓名：" prop="linkName">
              <p v-if="pageState == 1">{{formData.linkName}}</p>
              <el-input v-else class="add-input" type="text" maxlength="16" clearable
                        @keyup.native='replace(changeFormData.linkName,changeFormData,"linkName")' v-model="changeFormData.linkName"></el-input>
            </el-form-item>

            <el-form-item label="手机号：" prop="linkPhone">
              <p v-if="pageState == 1">{{formData.linkPhone}}</p>
              <el-input v-else class="add-input" type="text" maxlength="11" clearable
                        @keyup.native='replace(changeFormData.linkPhone,changeFormData,"linkPhone")' v-model="changeFormData.linkPhone"></el-input>
            </el-form-item>

            <el-form-item label="固定电话：" prop="fixPhone">
              <p v-if="pageState == 1">{{formData.fixPhone}}</p>
              <el-input v-else class="add-input" type="text" maxlength="11" clearable
                        @keyup.native='replace(changeFormData.fixPhone,changeFormData,"fixPhone")' v-model="changeFormData.fixPhone"></el-input>
            </el-form-item>

            <el-form-item label="邮箱：" prop="email">
              <p v-if="pageState == 1">{{formData.email}}</p>
              <el-input v-else class="add-input" type="text" clearable
                        @keyup.native='replace(changeFormData.email,changeFormData,"email")' v-model="changeFormData.email"></el-input>
            </el-form-item>

            <el-form-item label="统一社会信用代码：" prop="creditCode" style="text-align: left;">
              <p v-if="pageState == 1" class="personal-password">{{formData.creditCode}}</p>
              <el-input v-else class="add-input" maxlength="18" clearable
                        @keyup.native='replace(changeFormData.creditCode,changeFormData,"creditCode")' v-model="changeFormData.creditCode"></el-input>
            </el-form-item>

            <el-form-item label="法人姓名：" prop="principal">
              <p v-if="pageState == 1">{{formData.principal}}</p>
              <el-input v-else class="add-input" clearable maxlength="16"
                        @keyup.native='replace(changeFormData.principal,changeFormData,"principal")' v-model="changeFormData.principal"></el-input>
            </el-form-item>

            <el-form-item label="地址：" prop="address">
              <p v-if="pageState == 1">{{formData.address}}</p>
              <el-input v-else class="add-input" v-model="changeFormData.address" maxlength="100" clearable></el-input>
            </el-form-item>

            <el-form-item label="营业执照：" prop="licenseUrl">
              <img :src="formData.licenseUrl" class="headeImg" v-if="pageState == 1">
              <el-upload v-else class="avatar-uploader" action="1" :show-file-list="false" :before-upload="beforeUpload" :http-request="uploadImg1">
                <img v-if="changeFormData.licenseUrl" :src="changeFormData.licenseUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>

            <el-form-item label="法人身份证号：" prop="idcardNumber">
              <p v-if="pageState == 1">{{formData.idcardNumber}}</p>
              <el-input v-else class="add-input" clearable maxlength="18"
                        @keyup.native='replace(changeFormData.idcardNumber,changeFormData,"idcardNumber")' v-model="changeFormData.idcardNumber"></el-input>
            </el-form-item>

            <el-form-item label="身份证正面照：" prop="idcardFront">
              <img :src="formData.idcardFront" class="headeImg" v-if="pageState == 1">
              <el-upload v-else class="avatar-uploader" action="1" :show-file-list="false" :before-upload="beforeUpload" :http-request="uploadImg2">
                <img v-if="changeFormData.idcardFront" :src="changeFormData.idcardFront" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>

            <el-form-item label="身份证反面照：" prop="idcardReverse">
              <img :src="formData.idcardReverse" class="headeImg" v-if="pageState == 1">
              <el-upload v-else class="avatar-uploader" action="12" :show-file-list="false" :before-upload="beforeUpload" :http-request="uploadImg3">
                <img v-if="changeFormData.idcardReverse" :src="changeFormData.idcardReverse" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>

            <el-form-item label="食品流通许可证号：" prop="foodLicenseNumber">
              <p v-if="pageState == 1">{{formData.foodLicenseNumber}}</p>
              <el-input v-else class="add-input" clearable maxlength="18"
                        @keyup.native='replace(changeFormData.foodLicenseNumber,changeFormData,"foodLicenseNumber")' v-model="changeFormData.foodLicenseNumber"></el-input>
            </el-form-item>

            <el-form-item label="食品流通许可证：" prop="foodUrl">
              <img :src="formData.foodUrl" class="headeImg" v-if="pageState == 1 && formData.foodUrl">
              <el-upload v-else-if='pageState == 2' class="avatar-uploader" action="123" :show-file-list="false" :before-upload="beforeUpload" :http-request="uploadImg4">
                <img v-if="changeFormData.foodUrl" :src="changeFormData.foodUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>

            <el-form-item label="注册资金(万元)：" prop="registeredCapital">
              <p v-if="pageState == 1">{{formData.registeredCapital}}</p>
              <el-input v-else class="add-input" type="text" maxlength = '15' v-model="changeFormData.registeredCapital"
                        @keyup.native='replace(changeFormData.registeredCapital,changeFormData,"registeredCapital")' clearable></el-input>
            </el-form-item>

<!--            <el-form-item label="是否租户：" prop="isTenant">-->
<!--              <p v-if="pageState == 1">{{formData.isTenant == 1 ? '是' : '否'}}</p>-->
<!--              <el-select v-model="changeFormData.isTenant" placeholder="请选择" v-else style="width: 100%;">-->
<!--                <el-option v-for="( value, index) in option" :label="value.label" :value="value.value" :key="index"></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->

<!--            <el-form-item label="是否门店：" prop="isStore">-->
<!--              <p v-if="pageState == 1">{{formData.isStore == 1 ? '是' : '否'}}</p>-->
<!--              <el-select v-model="changeFormData.isStore" placeholder="请选择" v-else style="width: 100%;">-->
<!--                <el-option v-for="( value, index) in option" :label="value.label" :value="value.value" :key="index"></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->

          </el-form>
          <div class="application-btn">
            <el-button type="primary" plain @click="cancel()">返 回</el-button>
            <el-button type="primary" v-if="pageState == 0 || pageState == 2" native-type="submit" @click="submit()">提 交</el-button>
          </div>
        </div>
      </div>
      <!--弹框-->
      <el-dialog title="驳回原因" :visible.sync="dialogVisible" width="40%" center :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false">
        <p class="reject-reason">{{reason}}</p>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogVisible = false" plain>确 定</el-button>
          <el-button type="primary" @click="editForm()">修改提交资料</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Cookies from 'js-cookie'
import util from '@/util'
import { applyUpdateMerchant, uploadFile, findMerchantByMerchantId, findUserSubMerchant, getFile } from "@/api";
export default {
    name: "entry-application",
    data() {
        const checkMobile = (rule, value, callback) => {
            if (!util.validMobilePhone(value)) {
                return callback(new Error('手机号格式不正确 '));
            } else {
                callback();
            }
        };
        const validTelPhone = (rule, value, callback) => {
            if(value && !util.validTelPhone(value)) {
                return callback(new Error('固定电话格式不正确 '));
            } else {
              callback();
            }
        };
        const validSocialCreditCode = (rule, value, callback) => {
            if(value && !util.validSocialCreditCode(value)) {
                return callback(new Error('格式不正确(18位数字或者大写英文字母)！'));
            } else {
              callback();
            }
        };
        const validIdentity = (rule, value, callback) => {
            if(!util.validIdentity(value)) {
                return callback(new Error('身份证号码格式不正确！'));
            } else {
              callback();
            }
        };
      const validEmail  = (rule, value, callback) => {
        if(!util.validEmail(value)) {
          return callback(new Error('邮件格式不正确！'));
        }  else {
          callback();
        }
      };
      const validChineseAndBracket  = (rule, value, callback) => {
        if(!util.validChineseAndBracket(value)) {
          return callback(new Error('此处只能输入汉字或者括号!'));
        }  else {
          callback();
        }
      };
      const validRegisteredCapital = (rule, value, callback)=> {
        if(value && !util.validFloatNumber(value)) {
          return callback(new Error('此处只能输入数字或者小数点！'));
        } else if(value && String(value).indexOf('.')>0){
          let arr = value.split('.')
          if(value && arr[0].length>12){
            return callback(new Error('整数部分不能超过12位！'));
          }  else {
            callback();
          }
        }else {
          callback();
        }
      }
        return {
            pageState: 4, // 0 新增  1 查看  2 修改 4 隐藏
            formShow: false, // 显示表单
            dialogVisible: false, //显示弹窗
            labelPosition: "left", // 
            reason: "", // 驳回原因
            rules: {
                name: [{ required: true, message: '请输入商户名称', trigger: 'blur' },
                  {validator: validChineseAndBracket , trigger: 'blur' }],
                principal: [{ required: true, message: '请输入法人姓名', trigger: 'blur' }],
                fixPhone: [{validator: validTelPhone, trigger: 'blur'}],
                linkPhone: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { validator: checkMobile, trigger: 'blur'}],
                address: [{ required: true, message: '请输入商户地址', trigger: 'blur' }],
                creditCode: [{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' }, {validator: validSocialCreditCode, trigger: 'blur'}],
                licenseUrl: [{ required: true, message: '请上传营业执照图片', trigger: 'blur' }],
                idcardNumber: [{ required: true, message: '请输入身份证号码', trigger: 'blur' }, {validator: validIdentity, trigger: 'blur'}],
                idcardFront: [{ required: true, message: '请上传身份证正面照片', trigger: 'blur' }],
                idcardReverse: [{ required: true, message: '请上传身份证反面照片', trigger: 'blur' }],
                isTenant: [{ required: true, message: '请选择是否租户', trigger: 'blur' }],
                isStore: [{ required: true, message: '请选择是否门店', trigger: 'blur' }],
                email:[{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
                  {validator: validEmail, trigger: 'blur'}],
                linkName: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
                registeredCapital: [{validator: validRegisteredCapital, trigger: 'blur'}],
                foodLicenseNumber:[{validator: validSocialCreditCode, trigger: 'blur'}],
              },
            formData: {
                name: "",
                linkPhone: "",
                fixPhone: "",
                creditCode: "",
                principal: "",
                address: "",
                licenseUrl: "",
                idcardNumber: "",
                idcardFront: "",
                idcardReverse: "",
                foodLicenseNumber: "",
                foodUrl: "",
                registeredCapital: "",
                isTenant: null,
                isStore: null,
                linkName: '',
                email: '',
            },
            changeFormData: {
                name: "",
                linkPhone: "",
                fixPhone: "",
                creditCode: "",
                principal: "",
                address: "",
                licenseUrl: "",
                idcardNumber: "",
                idcardFront: "",
                idcardReverse: "",
                foodLicenseNumber: "",
                foodUrl: "",
                registeredCapital: "",
                isTenant: 0,
                isStore: 1,
                linkName: '',
                email: '',
            },
            option: [{
                    value: 1,
                    label: '是'
                }, {
                    value: 0,
                    label: '否'
                }
            ],
        }
    },
    computed: mapState(["applicationState", "userId", "merchantId", "mobile"]),
    mounted() {
      if (this.merchantId) {
        this.getData(this.merchantId)
      }
    },
    methods: {
      // 冗余请求 (注释超一个月后删除)
      // getMerchants(userId) {
      //   let data={
      //     userId: userId,
      //     phone: this.mobile
      //   }
      //   findUserSubMerchant(data).then((res)=> {
      //      if (+res.code == 200) {
      //        if(res.data.merchantList.length>0) {
      //          this.$store.commit("SET_ISENTRY", true);
      //           // 只有一个商户  商户状态为待审核或者驳回
      //          if (res.data.merchantList.length == 1 && res.data.merchantList[0].auditState != 1) {
      //             Cookies.set(process.env.COOKIE_NAME + '_merchantId', res.data.merchantList[0].merchantId)
      //             this.$store.commit("SET_APPLICATIONSTATE", res.data.merchantList[0].auditState);
      //          }else{
      //             util.routerReplace("/home/select-model");
      //          }
      //        } else {
      //          this.$store.commit("SET_ISENTRY", false);
      //          util.routerReplace('/application/entry-application');
      //        }
      //      }
      //   })
      // },
      replace(value,obj,key) {
        let that = this
        let event = event || window.event
        if(event.keyCode == 13){
          setTimeout(()=>{
            that.validItem(value,obj,key);
          },100);
        } else {
          that.validItem(value,obj,key);
        }
      },
      validItem(value,obj,key){
        let res = ''
        switch (key) {
          case 'name':
            res = util.replaceChineseAndBracket(value);
            break;
          case 'linkName':
          case 'principal':
            res = util.replaceChineseAndLetter(value);
            break;
          case 'linkPhone':
          case 'mobile':
            res = util.replaceNumber(value);
            break;
          case 'fixPhone':
            res = util.replaceFixPhone(value);
            break;
          case 'email':
            res = util.replaceEmail(value);
            break;
          case 'creditCode':
          case 'idcardNumber':
          case 'foodLicenseNumber':
            res = util.replaceSocialCreditCode(value);
            break;
          case 'registeredCapital':
            res = util.replaceTotal(value,12);
            break;
        }
        this.$set(obj,key,res);
      },
      look() {
        this.pageState = 1
      },
      cancel() {
        this.pageState = 4
        this.changeFormData = {
            name: "",
            linkPhone: "",
            fixPhone: "",
            creditCode: "",
            principal: "",
            address: "",
            licenseUrl: "",
            idcardNumber: "",
            idcardFront: "",
            idcardReverse: "",
            foodLicenseNumber: "",
            foodUrl: "",
            registeredCapital: "",
            isTenant: 0,
            isStore: 1,
            linkName: '',
            email: ''
        }
        // 冗余请求 (注释超一个月后删除)
        // this.getMerchants(this.userId)
        this.getData(this.merchantId)
      },
      submit() {
        this.$refs.formData.validate((valid) => {
          if(valid) {
            this.changeFormData.userId = this.userId;
            if(this.changeFormData.registeredCapital == '') {
              this.changeFormData.registeredCapital = 0
            }
            this.changeFormData.merchantId = this.merchantId
            applyUpdateMerchant(this.changeFormData).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                if (res.data.merchantId) {
                  this.$store.commit("SET_MERCHANTID", res.data.merchantId);
                  Cookies.set(process.env.COOKIE_NAME + '_merchantId', res.data.merchantId)
                }
                this.$store.commit("SET_APPLICATIONSTATE", 0);
                this.pageState = 1
                this.getData(res.data.merchantId || Cookies.get(process.env.COOKIE_NAME + '_merchantId'))
              } else {
                this.$message({
                  message: res.msg,
                  type: 'error'
                });
              }
            });
          }
        })
      },
      getData (merchantId) {
        findMerchantByMerchantId({
          merchantId: merchantId || Cookies.get(process.env.COOKIE_NAME + '_merchantId')
        }).then(res => {
          if (res.code == 200) {
            this.$store.commit("SET_APPLICATIONSTATE", res.data.auditState);
            this.formData = res.data
            this.reason = res.data.reasonRejection
          }
        })
      },
      goApplication() {
        this.pageState = 0
      },
      editForm() {
        this.dialogVisible = false
        this.changeFormData = JSON.parse(JSON.stringify(this.formData))
        this.pageState = 2
      },
      beforeUpload(file) {
        let isJPG = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg';
        let isLt0M = file.size;
        let isLt10M = file.size / 1024 / 1024 < 10;
        if (!isJPG) {
          this.$message.error('上传头像只能为png/jpg/jpeg格式');
        }
        if (!isLt0M || !isLt10M) {
          this.$message.error('上传头像图片大小必须大于0字节并且小于10M!');
        }
        return isJPG && isLt0M && isLt10M;
      },
      //上传图片
      uploadImg1(param) {
        let fileObj = param.file;
        let data = new FormData();
        data.append("file", fileObj);
        data.append("projectName", fileObj.name);
        uploadFile(data).then((res) =>{
          if(res.code == 200) {
            this.changeFormData.licenseUrl = `${getFile}?id=${res.data.id}`
          }else {
            this.$message({
              message: '图片上传失败',
              type: 'error'
            });
          }
        })
      },
      uploadImg2(param) {
        let fileObj = param.file;
        let data = new FormData();
        data.append("file", fileObj);
        data.append("projectName", fileObj.name);
        uploadFile(data).then((res) =>{
          if(res.code == 200) {
            this.changeFormData.idcardFront = `${getFile}?id=${res.data.id}`
          }else {
            this.$message({
              message: '图片上传失败',
              type: 'error'
            });
          }
        })
      },
      uploadImg3(param) {
        let fileObj = param.file;
        let data = new FormData();
        data.append("file", fileObj);
        data.append("projectName", fileObj.name);
        uploadFile(data).then((res) =>{
          if(res.code == 200) {
            this.changeFormData.idcardReverse = `${getFile}?id=${res.data.id}`
          }else {
            this.$message({
              message: '图片上传失败',
              type: 'error'
            });
          }
        })
      },
      uploadImg4(param) {
        let fileObj = param.file;
        let data = new FormData();
        data.append("file", fileObj);
        data.append("projectName", fileObj.name);
        uploadFile(data).then((res) =>{
          if(res.code == 200) {
            this.changeFormData.foodUrl = `${getFile}?id=${res.data.id}`
          }else {
            this.$message({
              message: '图片上传失败',
              type: 'error'
            });
          }
        })
      }
      },
    }
</script>

<style lang='less' scoped>
.application-page {
  margin-left: -11px;
  height: 100%;
  display: flex;
  display: -webkit-flex;
  justify-content: flex-start;
  overflow: hidden;
  .application-side {
    border-right: 1px solid #e6e6e6;
    padding-top: 15px;
    background: #fff;
    width: 209px;
    height: 100%;

    span {
      background: #dbf0fd;
      color: #2da3ea;
      height: 56px;
      line-height: 56px;
      display: block;
      font-size: 14px;
      text-indent: 20px;
    }
  }
  .application-main {
    flex: 1;
    height: 100%;
    width: 100%;
    padding-left: 10px;
    margin-top: 15px;
    background: #fff;
    position: relative;
    .wrap{
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        overflow: auto;
        padding: 20px 11px 11px 40px;
    }
    .application-status {
      font-size: 14px;
      text-align: left;
      .application-status-line {
        padding-top: 10px;
        .application-status-des {
          padding-top: 30px;
        }
      }
    }
    .application-form {
        width: 700px;
        padding-top: 20px;
        .application-btn {
            padding: 20px 0 40px 140px;
        }
        .avatar-uploader {
            text-align: left;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 300px;
            height: 150px;
            line-height: 150px;
            text-align: center;
        }
        .avatar {
            width: auto;
            height: 200px;
            display: block;
        }
    }
  }
}
</style>
<style lang="less">
.application-page{
    .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .el-upload:hover {
        border-color: #409eff;
    }
    .headeImg{
        width: auto;
        height: 200px;
        display: block;
        float: left;
    }
    .el-form-item__content{
        text-align: left;
    }
}
</style>
